問題の説明
文字列形式の辞書のリストを Python のデータフレームに変換する方法はありますか? (Is there a way to convert list of string formatted dictionary to a dataframe in Python?)
beautifulsoup の使い方を練習していますが、結果をデータフレームに変換できないため、現在漬け物になっています。
この例では、スクレイピングしたいページは以下を使用して取得できます:
from bs4 import BeautifulSoup
import requests
import pandas as pd
page = requests.get("https://store.moncler.com/en‑ca/women/autumn‑winter/view‑all‑outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0‑9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')
以下を使用して製品セクションに切り分けることができましたコード
test_class = []
for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf‑‑moncler'):
for test in section_tag.find_all('article'):
test_class.append(test.get('data‑ytos‑track‑product‑data'))
この結果は、次のような文字列形式の辞書のリストです:
['{"product_position" :0,"product_title":"TREPORT","product_brand":"モンクレール","product_category":"3074457345616676837/3074457345616676843","product_micro_category":"アウター","
リファレンスソリューション
方法 1:
Looks like the question really is about how to parse a string, not how to do something with pandas.
The list you have seem to contain simply valid json strings. You can convert them to python dict's using
json.loads()
from the standard lib. Of course if some strings are malformed that's another story, you'll have to google how to parse malformed jsons.After getting a list of python dicts turning them into a DataFrame is trivial.
方法 2:
you can use
json.loads
and then instantiatepandas.DataFrame
with the obtained list of dictionaries:d = [json.loads(e) for e in data] df = pd.DataFrame(d)
(by umm、ribitskiyb、kederrac)
リファレンスドキュメント